package com.syy.api.system.impl;
import cn.hutool.core.collection.CollUtil;
import com.syy.api.system.mapper.AdminUserMapper;
import com.syy.api.system.mapper.UserPostMapper;
import com.syy.api.system.service.AdminUserService;
import com.syy.common.core.domain.entity.SysUser;
import com.syy.common.enums.CommonStatusEnum;
import com.syy.system.domain.SysUserPost;
import com.syy.system.sms.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import static com.syy.common.enums.ErrorCodeConstants.USER_IS_DISABLE;
import static com.syy.common.enums.ErrorCodeConstants.USER_NOT_EXISTS;
import static com.syy.common.exception.ServiceExceptionUtil.exception;
import static com.syy.system.sms.CollectionUtils.convertSet;

@Service
@Slf4j
public class AdminUserServiceImpl implements AdminUserService{

    @Autowired
    private AdminUserMapper userMapper;

    @Resource
    private UserPostMapper userPostMapper;

    @Override
    public List<SysUser> getUserList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return userMapper.selectBatchIds(ids);
    }

    @Override
    public SysUser getUser(Long id) {
        SysUser sysUser = userMapper.selectById(id);
        return sysUser;
    }

    @Override
    public List<SysUser> getUserListByDeptIds(Collection<Long> deptIds) {
        if (CollUtil.isEmpty(deptIds)) {
            return Collections.emptyList();
        }
        return userMapper.selectListByDeptIds(deptIds);
    }

    @Override
    public void validateUserList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return;
        }
        // 获得岗位信息
        List<SysUser> users = userMapper.selectBatchIds(ids);
        Map<Long, SysUser> userMap = CollectionUtils.convertMap(users, SysUser::getUserId);
        // 校验
        ids.forEach(id -> {
            SysUser user = userMap.get(id);
            if (user == null) {
                throw exception(USER_NOT_EXISTS);
            }
            if (!CommonStatusEnum.ENABLE.getStatus().equals(user.getStatus())) {
                throw exception(USER_IS_DISABLE, user.getNickName());
            }
        });
    }

    @Override
    public List<SysUser> getUserListByPostIds(Collection<Long> postIds) {
        if (CollUtil.isEmpty(postIds)) {
            return Collections.emptyList();
        }
        Set<Long> userIds = convertSet(userPostMapper.selectListByPostIds(postIds), SysUserPost::getUserId);
        if (CollUtil.isEmpty(userIds)) {
            return Collections.emptyList();
        }
        return userMapper.selectBatchIds(userIds);
    }
}
